package com.leTest.eduService.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leTest.eduService.entity.ChapterEntity;
import com.leTest.eduService.entity.VideoEntity;
import com.leTest.eduService.entity.chapter.ChapterVo;
import com.leTest.eduService.entity.chapter.VideoVo;
import com.leTest.eduService.mapper.ChapterMapper;
import com.leTest.eduService.service.ChapterService;
import com.leTest.eduService.service.VideoService;
import com.leTest.exceptionhandler.CustomExceptionHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author le
 * @since 2025-02-16
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, ChapterEntity> implements ChapterService {

    @Autowired
    private VideoService videoService;

    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {

        QueryWrapper<ChapterEntity> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id", courseId);
        List<ChapterEntity> chapterList = baseMapper.selectList(chapterWrapper);

        QueryWrapper<VideoEntity> videpWrapper = new QueryWrapper<>();
        videpWrapper.eq("course_id", courseId);
        List<VideoEntity> videoList = videoService.list(videpWrapper);

        List<ChapterVo> resultList = new ArrayList<>();

        for (ChapterEntity chapterEntity : chapterList) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapterEntity, chapterVo);

            List<VideoVo> videoVoList = new ArrayList<>();
            for (VideoEntity videoEntity : videoList) {
                if (videoEntity.getChapterId().equals(chapterEntity.getId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(videoEntity, videoVo);
                    videoVoList.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVoList);
            resultList.add(chapterVo);
        }

        return resultList;
    }

    //删除章节的方法
    @Override
    public boolean deleteChapter(String chapterId) {
        //根据章节id(chapterid)查询小节表(edu_video),若能查到数据,就不删除该章节
        QueryWrapper<VideoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id", chapterId);
        int count = (int) videoService.count(wrapper);
        //判断
        if (count > 0) { //该章节下有小节,不删除该章节
            throw new CustomExceptionHandler(100, "不删除");
        } else { //该章节下没有小节,删除该章节
            int result = baseMapper.deleteById(chapterId);
            return  result > 0;
        }
    }
}
